#include "board_gui.h"

board_gui::board_gui(QWidget *parent) :
    QWidget(parent)
{
    size = 40;

    setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
    setMinimumSize(size*11, size*11);

}

void board_gui::paintEvent(QPaintEvent *event)
{
    qDebug() << "board::paintEvent()";

    double n = 10;
    int radius = size / 4;

    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing, true);
    //painter.setViewport(p.x(),p.y(),side,side);
    painter.setWindow(0, 0, size*(n+1.0), size*(n+1.0));


    painter.fillRect(QRect(0,0,size*(11),size*(11)), Qt::black);
    //painter.fillRect(QRect(0,size*(n+0.5),size*(n+1.0),size*0.5), Qt::blue);
    //painter.fillRect(QRect(0,0,size*(0.5),size*(n+1.0)), Qt::yellow);
    //painter.fillRect(QRect(size*(n+0.5),0,size*0.5,size*(n+1.0)), Qt::green);

    //i == y, j == x (y,x)
    for(int i=0; i<n; i++)
    {
        for(int j=0; j<n; j++)
        {
            QRect rect = returnRect(i, j);
            if( !((i+j%2)%2) )
            {

                painter.fillRect(rect, Qt::gray);
                //painter.drawEllipse(QPoint(zoom*(i+1),zoom*(10-j)),s,s);
            }
            else
            {
                painter.fillRect(rect, Qt::white);
            }

            // If that spot is owned, paint that piece
            if(board.grid[i][j].owner != 0)
            {
                // Set color to red
                if(board.grid[i][j].color == 'r')
                {
                    painter.setBrush(Qt::red);
                    painter.setPen(Qt::red);
                    painter.drawEllipse(QPoint((size*(i+1)), (size*(j+1))) , radius, radius);
                }

                // Set color to green
                else
                {
                    painter.setBrush(Qt::green);
                    painter.setPen(Qt::green);
                    painter.drawEllipse(QPoint((size*(i+1)), (size*(j+1))) , radius, radius);

                }
            }
        }
    }
}

void board_gui::mousePressEvent(QMouseEvent *event)
{
    int i = event->x();
    int j = event->y();

    if(event->buttons() && Qt::LeftButton)
    {
        if(i >= 20 && i < 420)
        {
            if(j >= 20 && j < 420)
            {
                int x = (i - 20) / 40;
                int y = (j - 20) / 40;
                board.grid[x][y].owner = 1;
                board.grid[x][y].color = 'g';
                update();
            }
        }
    }
}

QRect board_gui::returnRect(int i, int j) //const
{
        return QRect(size * i + size*0.5, size*(0.5) + size * j, size, size);
}
